﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PS3Helpers;
using PS3Helpers.Helpers;
using System.IO;

namespace PS3Packager
{
    public partial class CompilationProgressForm : Form, OutputLogInterface
    {
        ThreadBase _thread;

        public CompilationProgressForm()
        {
            InitializeComponent();
        }

        public void ShowDialog(ThreadBase thread, PS3PackageFile packagefile)
        {
            _thread = thread;

            labelProjectName.Text = Path.GetFileName(packagefile.Filename);
            labelPackageStep.Text = "";
            labelCurrentStatus.Text = "";

            _thread.ThreadEnded += new ThreadBase.ThreadEndedHandler(_thread_ThreadEnded);
            _thread.Start();
            base.ShowDialog();
        }

        private delegate void SetCurrentStepDelegate(string step);
        public void SetCurrentStep(string step)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new SetCurrentStepDelegate(SetCurrentStep), step);
                return;
            }

            labelPackageStep.Text = step;
            labelCurrentStatus.Text = "";
        }

        private delegate void SetCurrentStatusTextDelegate(string status);
        public void SetCurrentStatus(string status)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new SetCurrentStatusTextDelegate(SetCurrentStatus), status);
                return;
            }

            labelCurrentStatus.Text = status;
            this.toolTip.SetToolTip(labelCurrentStatus, status);
        }

        private delegate void SetCurrentStatusExceptionDelegate(Exception exception);
        public void SetCurrentStatus(Exception exception)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new SetCurrentStatusExceptionDelegate(SetCurrentStatus), exception);
                return;
            }

            labelCurrentStatus.Text = exception.Message;
            this.toolTip.SetToolTip(labelCurrentStatus, exception.Message);
        }

        public void WriteDebug(string text)
        {
            // Do nothing on the debug strings here...
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            if (_thread.Alive)
            {
                _thread.Terminate();
            }
            else
            {
                DialogResult = DialogResult.OK;
            }
        }

        private void _thread_ThreadEnded(ThreadBase sender, Exception endexception)
        {
            buttonCancel.Text = "Ok";

            if (endexception == null) SetCurrentStatus("Done");
            else SetCurrentStatus(endexception);
        }
    }
}
